/**
 * Created by zq on 2015/4/30.
 */

_.templateSettings = {
    evaluate    : /<#([\s\S]+?)#>/g,
    interpolate : /<#=([\s\S]+?)#>/g,
    escape      : /<#-([\s\S]+?)#>/g
};
var search = {
    sort:['default','popularity','sales','price'],
    hashset:function(obj){
        var OBJ = obj;
        $.each(obj,function(i,o){
            OBJ[i] = '-'+o.toString();
        });
        console.log('变成string后'+JSON.stringify(obj));
       return 'keyword'+obj.keyword+'/sort'+obj.sort+'/price'+obj.price+'/min'+obj.min+'/max'+obj.max+'/pno'+obj.pno+'/psize'+obj.psize;
    },
    changehash:function(obj){
        search.urlquery.set(obj,{validate:true});
        var newobj = $.extend({},this.urlquery.attributes);
        var newattr = this.hashset(newobj);
        console.log('new hash:'+newattr);
        location.hash = encodeURI(newattr);
    },
    docBindkeydown:function(next){
        var _this = $(this);
        $(document).keydown(function(event){
            if(event.keyCode=='13'){
                var obj = {},val = _this.val()==''?0:_this.val();
                obj[_this.attr('tyv')] = val;
                next(obj);
            }
        })
    },changeHTML:function(data){
        console.log(data);
        var temp = _.template($('#searchtemp').html());
        $('.searchgoods .bbox').html(temp(data.list));
        _.each(data.list,function(i,o){
            var a = o;
        })
    },
    getUrldata:function(){
        var urldata = $.extend({},arguments),a = function (w){return decodeURI(w.substring(1));};
        $.each(urldata,function(i,o){
            urldata[i] = a(o);
            console.log(i+':'+o);
        });
        console.log(JSON.stringify(urldata));
        search.urlquery.attributes = {
            keyword: urldata[0],
            sort: urldata[1],
            price: urldata[2],
            min: urldata[3],
            max: urldata[4],
            pno: urldata[5],
            psize: urldata[6]
        }
    }
};//default 默认排序 popularity 人气排序 sales 销量排序 price 价格排序
search.srcquery = Backbone.Model.extend({
    defaults:{
        keyword:$('#searchid').val(),
        sort:'default',
        price:'true',
        min:'0',
        max:'0',
        pno:'0',
        psize:'10'
    },validate: function(attrs, options) {
        console.log('验证的参数是'+JSON.stringify(attrs)+'--'+JSON.stringify(options));
        if (attrs.end < attrs.start) {
            return "can't end before it starts";
        }
    }
});
search.urlquery = new search.srcquery();
//search.changehash(search.urlquery.attributes);
search.router = Backbone.Router.extend({
    routes:{
        'keyword:keyword/sort:sort/price:price/min:min/max:max/pno:pno/psize:psize':'hashstart'
    },
    hashstart:function(keyword,sort,price,min,max,pno,psize){
        search.getUrldata.apply(this,arguments);
        var url = '/search/asearch',path = search.urlquery.attributes,
            fun = function(data){
                search.changeHTML(data);
            };
        $('#searchid').val(path.keyword);
        $.ajax({
            url:url,
            data:path,
            success:function(data){
                search.changeHTML(data);
            },
            error:function(){
                alert('djd');
            }
        });
    //请求数据
//        search.urlquery = new search.srcquery({
//            keyword:(keyword),
//            sort:sort,
//            price:Boolean(parseInt(price)),
//            min:parseInt(min),
//            max:parseInt(max),
//            pno:parseInt(pno),
//            psize:parseInt(psize)
//        });

    }
});
new search.router();
Backbone.history.start();
$('.btnlist .functionbtn').each(function(){
    $(this).click(function(){
        var this_ = $(this),adc = function(){
            $('.functionbtn').removeClass('act');
            this_.addClass('act');
        };
        if($.trim($(this).text())=='价格'){
            if($(this).find('i').length){
                if($.trim($(this).find('i')[0].className)=='up'){
                    adc();
                    $(this).find('i')[0].className = 'down';
                    search.changehash({'price':false,'sort':search.sort[3]});
                    return ;
                }
                adc();
                $(this).find('i')[0].className = 'up';
                search.changehash({'price':true,'sort':search.sort[3]});
                return ;
            }
            adc();
            $(this).append('<i class="up"></i>')
            return;
        }
        if($(this).hasClass('act'))
            return ;
        adc();
        search.changehash({'sort':search.sort[$(this).index()]});
    });
});
$('.number_o').each(function(){
    $(this).click(function(){
        $('.number_o').removeClass('act');
        $(this).addClass('act');
    })
});
$('[tyv]').focus(function(){
    search.docBindkeydown.call(this,function(o){
        search.changehash(o);
    });

}).blur(function(){
    $(document).unbind('keydown');
})